import { ref } from 'vue'
import { injectable } from '@/services/service'
import { readTextFile, exists, writeTextFile, BaseDirectory } from '@tauri-apps/api/fs'
import POIS from './pois'

export type Marker = {
  x: number,
  y: number,
  type: string
}

const identifier = 'tech.jiyun.ascum'

@injectable
/** 开门服务 */
export default class MarkerService {
  markers = ref([] as Marker[])
  constructor () {
    this.load()
  }

  add (x: number, y: number, type: string) {
    this.markers.value.push({
      x,
      y,
      type
    })
    this.save()
  }

  remove (i: number) {
    this.markers.value.splice(i, 1)
    this.save()
  }

  private async save () {
    try {
      await writeTextFile(identifier + '/pois.json', JSON.stringify(this.markers.value.map(v => ({
        ...v,
        x: v.x / window.outerHeight,
        y: v.y / window.outerHeight
      }))), { dir: BaseDirectory.Document })
    } catch { }
  }

  private async load () {
    if (!await exists(identifier + '/pois.json', { dir: BaseDirectory.Document })) {
      this.markers.value = POIS.map(v => ({
        ...v,
        x: v.x * window.outerHeight,
        y: v.y * window.outerHeight
      }))
      this.save()
      return
    }
    try {
      const markers = JSON.parse(await readTextFile(identifier + '/pois.json', { dir: BaseDirectory.Document })) as Marker[]
      if (Array.isArray(markers)) {
        this.markers.value = markers.map(v => ({
          ...v,
          x: v.x * window.outerHeight,
          y: v.y * window.outerHeight
        }))
      }
    } catch { }
  }
}
